package com.lqq.chapter09;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author lqq677
 * @Date 2021/8/12 10:46
 * @Description BlockingQueue案例
 */
public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {

        //创建容量为3的阻塞队列
        BlockingQueue<String> queue = new ArrayBlockingQueue(3);


        System.out.println("*********第一组 add(e), remove(), element()***********");
        System.out.println(queue.add("a"));//true
        System.out.println(queue.add("b"));//true
        System.out.println(queue.add("c"));//true
        //System.out.println(queue.add("d"));//队列满，抛出异常：java.lang.IllegalStateException: Queue full

        System.out.println(queue.element());//a 返回队首元素

        System.out.println(queue.remove());//a
        System.out.println(queue.remove());//b
        System.out.println(queue.remove());//c
        //System.out.println(queue.remove());//队列空，抛出异常:java.util.NoSuchElementException



        System.out.println("*********第二组 offer(e), poll(), peek()***********");
        System.out.println(queue.offer("a"));//true
        System.out.println(queue.offer("b"));//true
        System.out.println(queue.offer("c"));//true
        System.out.println(queue.offer("d"));//false，队列满，offer失败，返回false

        System.out.println(queue.peek());//a 返回队首元素

        System.out.println(queue.poll());//a
        System.out.println(queue.poll());//b
        System.out.println(queue.poll());//c
        System.out.println(queue.poll());//null，队列空返回null



        System.out.println("*********第三组 put(e), take()***********");
        // void put(E e) throws InterruptedException;
        queue.put("a");
        queue.put("b");
        queue.put("c");
        //queue.put("d");//队列满会阻塞直至队列可用

        //E take() throws InterruptedException;
        System.out.println(queue.take());//a
        System.out.println(queue.take());//b
        System.out.println(queue.take());//c
        //System.out.println(queue.take());//队列空会阻塞直至队列不为空



        System.out.println("*********第四组 offer(e, time, unit), poll(time, unit)***********");
        System.out.println(queue.offer("a", 3, TimeUnit.SECONDS));//true
        System.out.println(queue.offer("b", 3, TimeUnit.SECONDS));//true
        System.out.println(queue.offer("c", 3, TimeUnit.SECONDS));//true
        System.out.println(queue.offer("d", 3, TimeUnit.SECONDS));//false,队列满会阻塞3秒返回false

        System.out.println(queue.poll(3, TimeUnit.SECONDS));//a
        System.out.println(queue.poll(3, TimeUnit.SECONDS));//b
        System.out.println(queue.poll(3, TimeUnit.SECONDS));//c
        System.out.println(queue.poll(3, TimeUnit.SECONDS));//null,队列空会阻塞3秒返回null
    }
}
